//
//  TakePhotoViewController.swift
//  CalligraphyUniversal
//
//  Created by 李雷川 on 2017/3/27.
//  Copyright © 2017年 李雷川. All rights reserved.
//

import UIKit
import FZSFCommonTools
import AVFoundation

public class TakePhotoViewController: TakePhotoBaseViewController {
    fileprivate lazy var  captureSession:AVCaptureSession = AVCaptureSession()
    fileprivate var captureDevice:AVCaptureDevice?
    fileprivate var captureDeviceInput:AVCaptureDeviceInput?
    fileprivate var stillImageOutput:AVCaptureStillImageOutput?
    fileprivate var videoPreviewLayer:AVCaptureVideoPreviewLayer?
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        if isRightCamera(){
            setupDevice()
        }
        initUI()
    }

    
    override public var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }

    
    override public func viewDidAppear(_ animated: Bool) {
        startSession()
        takePhotoButton.isEnabled = true
    }
    
    
    override public func viewWillDisappear(_ animated: Bool) {
        stopSession()
    }

    override func startGeneragteImage(){
        
        if let connection = self.stillImageOutput?.connection(with: AVMediaType.video){
            stillImageOutput?.captureStillImageAsynchronously(from: connection, completionHandler: { [weak self](buffer, error) in
                self?.stopSession()
                guard let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer!) else{
                    self?.startSession()
                    self?.generateImageFaild()
                    return
                }
                guard let image = UIImage.init(data: imageData)else{
                    self?.startSession()
                    self?.generateImageFaild()
                    return
                }
                self?.generateImageSuccess(image: image)
            })
        }
    }
    
    func setupDevice(){
        if(configureCaptureSession()){
            setupVideoPreviewLayer()
        }
    }
    
    //根据设备类型获取摄像头
    func cameraWithPostion(postion:AVCaptureDevice.Position)->AVCaptureDevice?{
        let devices = AVCaptureDevice.devices(for: AVMediaType.video)
        for device in devices{
            if device.position == postion{
                return device
            }
        }
        return nil
    }
    
    
    
    func setupVideoPreviewLayer(){
        if(videoPreviewLayer == nil){
            videoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: captureSession)
            videoPreviewLayer?.backgroundColor = UIColor.black.cgColor
            videoPreviewLayer?.frame = view.bounds
            videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
            view?.layer.addSublayer(videoPreviewLayer!)
        }
    }


    
    
    @objc override func tapSwitchCamera(sender:UIButton){
        super.tapSwitchCamera(sender: sender)
        captureSession.beginConfiguration()
        captureSession.removeInput(captureDeviceInput!)
        if(isFrontCamera){
            captureDevice = cameraWithPostion(postion:.front)
        }
        else{
            captureDevice = cameraWithPostion(postion:.back)
        }
        //创建输入
        do{
            try captureDeviceInput = AVCaptureDeviceInput.init(device: captureDevice!)
            
        }
        catch{
            debugPrint("切换失败")
        }
        //连接输入与会话
        if(captureSession.canAddInput(captureDeviceInput!)){
            captureSession.addInput(captureDeviceInput!)
        }
        captureSession.commitConfiguration()
    }
    
    


}




//MARK:采集图片
extension TakePhotoViewController{
    func configureCaptureSession() ->Bool{
        //设置会话
        captureSession.sessionPreset = AVCaptureSession.Preset.photo
        //创建输入设备
        captureDevice =  cameraWithPostion(postion: .back)
        //创建输入
        do{
            try captureDeviceInput = AVCaptureDeviceInput.init(device: captureDevice!)
            
        }
        catch{
            return false
        }
        
        stillImageOutput = AVCaptureStillImageOutput()
        stillImageOutput?.outputSettings = [AVVideoCodecKey:AVVideoCodecJPEG]
        //连接输入与会话
        if(captureSession.canAddInput(captureDeviceInput!)){
            captureSession.addInput(captureDeviceInput!)
        }
        //连接输出与会话
        if(captureSession.canAddOutput(stillImageOutput!)){
            captureSession.addOutput(stillImageOutput!)
        }
        return true
    }
    
    func startSession(){
        if(self.captureSession.isRunning == false){
            self.captureSession.startRunning()
        }

    }
    
    func stopSession(){
        if(self.captureSession.isRunning == true){
            self.captureSession.stopRunning()
        }
    }
    

    
}



